using System;
using System.Text.Json;
using Microsoft.Maui.Controls;

namespace planning_lite
{
    public partial class SettingsPage : ContentPage
    {
        public SettingsPage()
        {
            InitializeComponent();
            AffectSettingsToPage();
        }

        private async void OnAboutClicked(object sender, EventArgs e)
        {
            // 显示关于信息
            await DisplayAlert("关于", "Planning Lite v1.0\nMade by half-tree 2025\nAll rights reserved", "确定");
        }

        private void AffectSettingsToPage()
        {
            Settings settings = MainPage.Settings;
            ServerAddressEntry.Text = settings.taskServerLocation;
            UserNameEntry.Text = settings.userName;
            SendPlanReminderSwitch.IsToggled = settings.sendPlanningMessage;
        }

        private async void OnConfirmSettingsClicked(object sender, EventArgs e)
        {
            try
            {
                Settings settings = new Settings
                {
                    taskServerLocation = ServerAddressEntry.Text.Trim(),
                    userName = UserNameEntry.Text.Trim(),
                    sendPlanningMessage = SendPlanReminderSwitch.IsToggled
                };
                settings.SaveCurrentSettings(settings);
                await DisplayAlert("提示", "设置已保存", "确定");
                MainPage.Settings = settings;
            }
            catch (Exception ex)
            {
                await DisplayAlert("错误", $"保存设置时发生错误：{ex.Message}", "确定");
            }
        }

        private async void OnBackClicked(object sender, EventArgs e)
        {
            // 返回主页面
            try
            {
                await Navigation.PopAsync();
            }
            catch (System.Exception)
            {
                await DisplayAlert("错误", "无法返回上一页，请稍后再试。", "确定");
            }
        }
    }
}